﻿# Claude Code 镜像同步脚本
# 从官方 Google Cloud Storage 下载文件并准备上传到 Gitee

param(
    [Parameter(Mandatory=$false)]
    [string]$OutputDir = ".\claude-mirror",
    
    [Parameter(Mandatory=$false)]
    [switch]$DownloadAllPlatforms = $false,
    
    [Parameter(Mandatory=$false)]
    [switch]$AutoCommit = $false,
    
    [Parameter(Mandatory=$false)]
    [string]$GiteeRepo = ""
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$ProgressPreference = 'SilentlyContinue'

$GCS_BUCKET = "https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases"

Write-Host "======================================" -ForegroundColor Cyan
Write-Host "  Claude Code Gitee 镜像同步工具" -ForegroundColor Cyan
Write-Host "======================================" -ForegroundColor Cyan
Write-Host ""

# 创建输出目录
New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null
Write-Host "[1/6] 创建输出目录: $OutputDir" -ForegroundColor Green

# 获取稳定版本号
Write-Host "[2/6] 获取稳定版本号..." -ForegroundColor Yellow
try {
    $version = Invoke-RestMethod -Uri "$GCS_BUCKET/stable" -ErrorAction Stop
    Write-Host "      稳定版本: $version" -ForegroundColor Green
}
catch {
    Write-Error "无法获取版本号。请检查网络连接或使用代理。错误: $_"
    exit 1
}

# 保存版本号文件
$version | Out-File -FilePath "$OutputDir\stable" -NoNewline -Encoding ASCII
Write-Host "      已保存 stable 文件" -ForegroundColor Green

# 获取 latest 版本号（可选）
try {
    $latest = Invoke-RestMethod -Uri "$GCS_BUCKET/latest" -ErrorAction Stop
    $latest | Out-File -FilePath "$OutputDir\latest" -NoNewline -Encoding ASCII
    Write-Host "      最新版本: $latest" -ForegroundColor Green
}
catch {
    Write-Warning "无法获取 latest 版本号（可能不存在）"
}

# 创建版本目录
$versionDir = "$OutputDir\$version"
New-Item -ItemType Directory -Force -Path $versionDir | Out-Null

# 下载 manifest.json
Write-Host "[3/6] 下载 manifest.json..." -ForegroundColor Yellow
try {
    $manifestUrl = "$GCS_BUCKET/$version/manifest.json"
    Invoke-WebRequest -Uri $manifestUrl -OutFile "$versionDir\manifest.json" -ErrorAction Stop
    Write-Host "      已下载 manifest.json" -ForegroundColor Green
    
    # 读取并显示 manifest 信息
    $manifest = Get-Content "$versionDir\manifest.json" | ConvertFrom-Json
    Write-Host "      可用平台:" -ForegroundColor Cyan
    $manifest.platforms.PSObject.Properties | ForEach-Object {
        Write-Host "        - $($_.Name)" -ForegroundColor Gray
    }
}
catch {
    Write-Error "下载 manifest.json 失败: $_"
    exit 1
}

# 下载二进制文件
Write-Host "[4/6] 下载二进制文件..." -ForegroundColor Yellow

$platforms = @()
if ($DownloadAllPlatforms) {
    # 下载所有平台
    $platforms = $manifest.platforms.PSObject.Properties.Name
    Write-Host "      将下载所有平台的文件" -ForegroundColor Cyan
}
else {
    # 只下载 Windows x64
    $platforms = @("win32-x64")
    Write-Host "      将下载 Windows x64 平台（使用 -DownloadAllPlatforms 下载所有平台）" -ForegroundColor Cyan
}

foreach ($platform in $platforms) {
    Write-Host "      下载 $platform..." -ForegroundColor Yellow
    
    $platformDir = "$versionDir\$platform"
    New-Item -ItemType Directory -Force -Path $platformDir | Out-Null
    
    try {
        $binaryUrl = "$GCS_BUCKET/$version/$platform/claude.exe"
        $binaryPath = "$platformDir\claude.exe"
        
        Write-Host "        从 $binaryUrl" -ForegroundColor Gray
        Invoke-WebRequest -Uri $binaryUrl -OutFile $binaryPath -ErrorAction Stop
        
        # 验证校验和
        $actualChecksum = (Get-FileHash -Path $binaryPath -Algorithm SHA256).Hash.ToLower()
        $expectedChecksum = $manifest.platforms.$platform.checksum
        
        if ($actualChecksum -eq $expectedChecksum) {
            Write-Host "        ✓ 校验和验证通过" -ForegroundColor Green
        }
        else {
            Write-Warning "        × 校验和不匹配！"
            Write-Warning "          期望: $expectedChecksum"
            Write-Warning "          实际: $actualChecksum"
        }
        
        # 显示文件大小
        $fileSize = (Get-Item $binaryPath).Length
        $fileSizeMB = [math]::Round($fileSize / 1MB, 2)
        Write-Host "        文件大小: $fileSizeMB MB" -ForegroundColor Gray
    }
    catch {
        Write-Warning "下载 $platform 失败: $_"
    }
}

# 生成文件清单
Write-Host "[5/6] 生成文件清单..." -ForegroundColor Yellow
$filesManifest = @{
    version = $version
    syncTime = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
    files = @()
}

Get-ChildItem -Path $OutputDir -Recurse -File | ForEach-Object {
    $relativePath = $_.FullName.Substring($OutputDir.Length + 1)
    $filesManifest.files += @{
        path = $relativePath
        size = $_.Length
        checksum = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash.ToLower()
    }
}

$filesManifest | ConvertTo-Json -Depth 10 | Out-File -FilePath "$OutputDir\files-manifest.json" -Encoding UTF8
Write-Host "      已生成文件清单: files-manifest.json" -ForegroundColor Green

# 显示目录结构
Write-Host "[6/6] 文件下载完成！" -ForegroundColor Green
Write-Host ""
Write-Host "目录结构:" -ForegroundColor Cyan
tree /F $OutputDir

Write-Host ""
Write-Host "======================================" -ForegroundColor Cyan
Write-Host "  下一步操作" -ForegroundColor Cyan
Write-Host "======================================" -ForegroundColor Cyan
Write-Host ""

if ($AutoCommit -and $GiteeRepo) {
    Write-Host "自动提交到 Gitee..." -ForegroundColor Yellow
    
    $tempCloneDir = ".\gitee-temp"
    
    try {
        # 克隆仓库
        Write-Host "  克隆 Gitee 仓库..." -ForegroundColor Gray
        git clone $GiteeRepo $tempCloneDir
        
        # 复制文件
        Write-Host "  复制文件..." -ForegroundColor Gray
        $destDir = "$tempCloneDir\claude-code-releases"
        New-Item -ItemType Directory -Force -Path $destDir | Out-Null
        Copy-Item -Path "$OutputDir\*" -Destination $destDir -Recurse -Force
        
        # 提交
        Write-Host "  提交更改..." -ForegroundColor Gray
        Push-Location $tempCloneDir
        git add .
        git commit -m "更新 Claude Code 到版本 $version"
        git push origin master
        Pop-Location
        
        Write-Host "  ✓ 已成功推送到 Gitee！" -ForegroundColor Green
        
        # 清理临时目录
        Remove-Item -Path $tempCloneDir -Recurse -Force
    }
    catch {
        Write-Error "自动提交失败: $_"
        Pop-Location
    }
}
else {
    Write-Host "1. 在 Gitee 上创建仓库（如果还没有）" -ForegroundColor White
    Write-Host "   https://gitee.com/projects/new" -ForegroundColor Gray
    Write-Host ""
    Write-Host "2. 将 '$OutputDir' 目录中的内容上传到 Gitee 仓库的 'claude-code-releases' 目录" -ForegroundColor White
    Write-Host ""
    Write-Host "   方法 A - 使用 Git 命令行:" -ForegroundColor White
    Write-Host "   git clone https://gitee.com/your-username/claude-code-mirror.git" -ForegroundColor Gray
    Write-Host "   mkdir claude-code-mirror\claude-code-releases" -ForegroundColor Gray
    Write-Host "   copy $OutputDir\* claude-code-mirror\claude-code-releases\ /E" -ForegroundColor Gray
    Write-Host "   cd claude-code-mirror" -ForegroundColor Gray
    Write-Host "   git add ." -ForegroundColor Gray
    Write-Host "   git commit -m `"添加 Claude Code $version`"" -ForegroundColor Gray
    Write-Host "   git push origin master" -ForegroundColor Gray
    Write-Host ""
    Write-Host "   方法 B - 使用本脚本自动上传:" -ForegroundColor White
    Write-Host "   .\sync-to-gitee.ps1 -AutoCommit -GiteeRepo `"https://gitee.com/your-username/claude-code-mirror.git`"" -ForegroundColor Gray
    Write-Host ""
    Write-Host "3. 修改 bootstrap.ps1 中的下载地址:" -ForegroundColor White
    Write-Host "   `$GCS_BUCKET = `"https://gitee.com/your-username/claude-code-mirror/raw/master/claude-code-releases`"" -ForegroundColor Gray
    Write-Host ""
    Write-Host "4. 测试安装脚本:" -ForegroundColor White
    Write-Host "   .\bootstrap.ps1" -ForegroundColor Gray
}

Write-Host ""
Write-Host "完成！" -ForegroundColor Green
